package frame.service.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import util.SecurityUtil;

import java.io.IOException;
import java.util.Formatter;
import java.util.UUID;

public class FrameUtil {
    /**
     * 服务ID管理 safeMode/module/service
     * */
    public static String generateServiceId(String safeMode, String module, String service){
        return safeMode+"/"+module+"/"+service;
    }

    /**
     * 操作ID管理 action-version
     * */
    public static String generateActionId(String action, String version){
        return action+"-"+version;
    }

    public static String stringFormatter(String source, Object[] attr){
        Formatter formatter = new Formatter();
        return formatter.format(source, attr).toString();
    }

    public static String generateSessionUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String generateSessionId(String sessionUUID, String sessionSecret){
        return SecurityUtil.sha256((sessionUUID+sessionSecret).getBytes());
    }

    public static String obj2json(Object obj){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static <T> T str2Obj(String str, Class t) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return (T) objectMapper.readValue(str.getBytes(), t);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
